package com.wuxinwudai.android.app;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.wuxinwudai.android.R;


/**
 * BaseFragment 类作为其他 Fragment 类的基类
 * @author 吾心无待 于2016年02月24日
 */
public abstract class BaseFragment extends Fragment {
    protected final String TAG = this.getClass().getCanonicalName();//TAG 调试标签
    protected View mContentView;//容器视图
    protected boolean mInOutAnim = true;//出入动画

    /**
     * 获取是否执行 Activity 进出动画
     * @return 是否执行 Activity 进出动画
     */
    public boolean getInOutAnim() {
        return mInOutAnim;
    }

    /**
     * 设置是否执行 Activity 进出动画
     * @param inOutAnim 是否执行 Activity 进进出动画
     */
    public void setInOutAnim(boolean inOutAnim) {
        this.mInOutAnim = inOutAnim;
    }
    @Override
    public void startActivity(Intent intent) {
        if (mInOutAnim) {
            getActivity().startActivity(intent);
            getActivity().overridePendingTransition(R.anim.slide_in_right_to_left, R.anim.slide_out_right_to_left);
        }else{
            super.startActivity(intent);
        }
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        if (mInOutAnim) {
            getActivity().startActivity(intent);
            getActivity().overridePendingTransition(R.anim.slide_in_right_to_left, R.anim.slide_out_right_to_left);
        }else{
            super.startActivity(intent);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mContentView == null){
            mContentView = LayoutInflater.from(getContext()).inflate(getLayoutResID(),null);
            initChildView(savedInstanceState);
        }else{
            ViewGroup parent = (ViewGroup)mContentView.getParent();
            if (parent != null){
                parent.removeView(mContentView);
            }
        }
        return mContentView;
    }

    /**
     * Fragment 下查找View
     *
     * @param id   控件的id
     * @param <VT> View类型
     * @return 子视图 View
     */
    protected <VT extends View> VT getViewById(@IdRes int id) {
        return (VT) mContentView.findViewById(id);
    }

    /**
     * 获取布局资源 id
     * @return 布局资源 id
     */
    protected abstract int getLayoutResID();

    /**
     * 初始化子视图
     */
    protected abstract void initChildView(@Nullable Bundle savedInstanceState);

    /**
     * 输出 info 信息
     * @param msg 信息
     */
    protected void i(String msg){
        Log.i(TAG,msg);
    }
}
